package com.oldroid.apps.getit.ui;
import java.io.File;
import java.net.URLConnection;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads;
import com.oldroid.apps.getit.ui.adapter.FileAdapter;

/*
SharedPreferences mPreferences;
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String latestPath;
if ((latestPath = mPreferences.getString("LATEST_PATH", null)) != null) {
*/


public class SearchFragment extends android.support.v4.app.ListFragment {
	private final String TAG = "FileBrowserFragment";
	private int mCurPosition = 0;
	private ListView mListView;
	private File mFile;
	//private File mFile2;
	private ArrayList<File> dirs;
	private Dialog mDialog;
	//private Dialog mChooseDirDialog;
	private SearchFragment mThis = this;
	private ContentResolver mURI;
	private Activity mActivity; 
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		SharedPreferences mPreferences;
		mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
		
		mActivity = getActivity(); 
		mURI = mActivity.getContentResolver(); 
		

	}

	public void setListTest(){
		
		String[] test = {"one", "two", "three", "four", "five"};
		
		ArrayAdapter<String> a = new ArrayAdapter<String>(getActivity(), R.layout.list_item_row, test);
		setListAdapter(a);
		
	}
	
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		
	}
	
	
	
	/**
	 * Shows the results of the search on to the list view
	 * @param cursor cursor containing the search results. 
	 */
	private void showResult(Cursor cursor){
		
//		String[] from = {Downloads.FILENAME};
//		int[] to = {R.id.list_item};
//		
//		SimpleCursorAdapter adapter = new SimpleCursorAdapter(mActivity, R.layout.list_item_row, cursor, from, to);
//		setListAdapter(adapter);
		
		int count = cursor.getCount(); 
		say("Search Returned " +  count + " Results.");
		
		// Create File Adapter
		ArrayList<File> files = new ArrayList<File>(20); 
		while(cursor.moveToNext()){
			String filePath = cursor.getString(cursor.getColumnIndex(Downloads.URI));
			files.add(new File(filePath)); 
		}
		setListAdapter(new FileAdapter(mActivity, R.layout.file_list_row, files));
			
		
		// Show no result msg if no results returned.
		if(count == 0){
			String[] msg = {"No Results Found"};
			ArrayAdapter<String> a = new ArrayAdapter<String>(getActivity(), R.layout.list_item_row, msg);
			setListAdapter(a);
		}
	}
	
	
	
	private void say(String msg){
		
		Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
	}
	
	
	
	
	/**.
	 * Opens the file on the system that matches the id in the downloads provider
	 * We guess the file type from the extension and if an appropriate program is found
	 * we call it to view the file. If no program exists capable of viewing the program, then the
	 * user is shown a dialog to that effect. 
	 * @param id the file id in the Downloads Content Provider to open. 
	 */
	public void openByID(String id){
		
		// Pull up the relevant record from the downloads provider
		String[] projection = null; // get all the columns
		String selection = Downloads._ID + " = " + id; // specify the id  
		String[] selectionArgs = null; // no binding the values here  
		String sortOrder = Downloads._ID + " ASC"; // ascending order 
		
		Cursor c = mActivity.managedQuery(Downloads.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		
		// check that the given file id exists
		if(!c.moveToFirst()){
			
			Log.e("SEARCH_SUGGEST", "Could not open file id = " + id + "because it does not actually exists in the database");
			return;
		}
		
		// Get the File Path
		String filePath = c.getString(c.getColumnIndex(Downloads.URI)); 
		File file = new File(filePath);
		Uri uri = Uri.fromFile(file);
		
		try {
			Intent i = new Intent(); 
			i.setAction(Intent.ACTION_VIEW);
			i.setDataAndType(uri, URLConnection.guessContentTypeFromName(file.getName()));
			startActivity(i); // open the file with the appropriate program. 
			
		} catch (ActivityNotFoundException e) {
			// TODO Auto-generated catch block
			AlertDialog alert = new AlertDialog.Builder(getView().getContext()).create(); 
			alert.setMessage("No Program capable of opening that file was found");
			alert.show(); 
		}  
		
		
	}
	
	/**
	 * Does a file ID search in the database
	 * @param query file ID of file in databae
	 */
	public void searchByID(String query){
		
		String [] projection = null ; // get all the columns
		String selection = Downloads._ID + " = " + query ; 
		String[] selectionArgs = null; // no binding the values here  
		String sortOrder = Downloads._ID + " ASC"; // ascending order 
		
		Cursor c = mActivity.managedQuery(Downloads.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
		showResult(c);
	}
	
	/**
	 * Searches the Downloads Database for downloaded files that match the given string query  
	 * @param query
	 */
	public void search(String query){
		
		String [] projection = null ; // get all the columns
		String selection = Downloads.DELETED + " = 0 AND " + Downloads.FILENAME + " LIKE '%" + query +"%'"; //Only search non-deleted files. Like statements tells SQL to do partial matching. 
		//String selection = Downloads.FILENAME + " LIKE '%" + query +"%'"; //Like statements tells SQL to do partial matching.
		String[] selectionArgs = null; // no binding the values here  
		String sortOrder = Downloads.FILENAME + " ASC"; // ascending order 
		
		Cursor c = mActivity.managedQuery(Downloads.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
	
		showResult(c);
		
	}
	
	
		
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		File fp = (File) l.getItemAtPosition(position); 
		
		try{
			Intent i = new Intent();
			i.setAction(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.fromFile(fp), URLConnection.guessContentTypeFromName(fp.getName()));
			startActivity(i);
		}
		catch(ActivityNotFoundException e) {
			Toast.makeText(getActivity(), "No program capable of opening that file was found.", Toast.LENGTH_SHORT).show();
		}
	
	}

	public void selectPosition(int position) {
		ListView lv = getListView();
		lv.setItemChecked(position, true);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("listPosition", mCurPosition);
	}

}